//
//  THSuggestViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/9.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THAddTieZiViewController.h"
#import "STTools_TextView.h"
@interface THAddTieZiViewController ()
@property(nonatomic, strong) UITextField                     *titleTextFiled;/**<  */
@property(nonatomic, strong) STTools_TextView                     *text_view;/**<  */
@property(nonatomic, strong) STTools_ImageAutoChoseView                     *autoView;/**<  */
@property(nonatomic, strong) NSMutableArray<NSArray*>                     *dataSouce;/**<  */
@property(nonatomic, strong) NSString                     *is_show;/**< 是否显示 */
@property(nonatomic, strong) NSString                     *posts_cate_id;/**< 分类id */
@property(nonatomic, strong) NSString                     *goods_id;/**<  */

@property(nonatomic, strong) NSMutableArray                     *imagesArray;/**<  */
@end

@implementation THAddTieZiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.is_show = @"1";
    self.tableView.backgroundColor = UIColor.whiteColor;
    
    if (self.model) {
        self.title = @"编辑";
        [self config_edit_info];
    }else{
        self.title = @"发资讯";
        [self config_tableHeader];
        [self config_dataSouce];
    }

    [self stoneobs_fun_st_setRightItemWithTitle:@"发布" titleColor:STONEOBS_UI_FIRST_TEXT_COLOR];
    // Do any additional setup after loading the view.
}
- (void)config_edit_info{
    NSMutableArray * array = NSMutableArray.new;
    
    dispatch_group_t group = dispatch_group_create();

    for (NSString * url in self.model.imgs) {
        dispatch_group_enter(group);
       
        [SDWebImageManager.sharedManager loadImageWithURL:url.mj_url options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image) {
                [array addObject:image];
            }
            dispatch_group_leave(group);
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        
        self.imagesArray = NSMutableArray.new;
        for (UIImage * image in array) {
            STBWPhotoModel * model =  STBWPhotoModel.new;
            model.originImage = image;
            [self.imagesArray addObject:model];
        }
        [self config_tableHeader];
        [self config_dataSouce];
        self.titleTextFiled.text = self.model.title;
        self.text_view.text = self.model.content;
        [self.autoView.dataSouce addObjectsFromArray:self.imagesArray];
        [self.autoView.collectionView reloadData];
        ({
            STTools_TableEasyModel * model = self.dataSouce[0].firstObject;
            model.detailString =  self.model.posts_cate_name;
            self.posts_cate_id = self.model.posts_cate_id;
        });
        ({
            STTools_TableEasyModel * model = self.dataSouce[0][1];
            model.detailString =  self.model.goods_name;
            self.goods_id = self.model.goods_id;
        });
        ({
            STTools_TableEasyModel * model = self.dataSouce[0][2];
            if (self.model.is_show) {
                model.detailString =  @"所有人";
                self.is_show = @"1";
            }else{
                model.detailString =  @"自己";
                self.is_show = @"0";
            }
        });
        [self config_tableHeader];
        [self.tableView reloadData];
    });
}
- (void)config_dataSouce{
    self.dataSouce = NSMutableArray.new;
    
    ({
       NSArray * array = @[
           [[STTools_TableEasyModel alloc] initWithTextString:@"分类" detailString:@"请选择"],
           [[STTools_TableEasyModel alloc] initWithTextString:@"添加购买体验" detailString:@"请选择"],
           [[STTools_TableEasyModel alloc] initWithTextString:@"谁可以看" detailString:@"所有人"],
       ];
        [self.dataSouce addObject:array];
    });
    
    [self.tableView reloadData];
}
#pragma mark --configSubView
- (void)config_tableHeader{
    UIView * header = [[UIView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    
    
    if (!self.titleTextFiled) {
        self.titleTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, STONEOBS_UI_UISCREEN_WIDTH - 24 - 20, 40)];
        self.titleTextFiled.placeholder = @"请输入标题";
        
    }
    
    [header addSubview:self.titleTextFiled];
    
    
    CGFloat top = self.titleTextFiled.bottom + 10;
    ({
        
        
        
        UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(12, top, STONEOBS_UI_UISCREEN_WIDTH - 24, 156)];
        whiteView.backgroundColor = WH_UICOLOR_FROM_RGBA(0xEEEEEE);
        whiteView.layer.cornerRadius = 8;
        whiteView.clipsToBounds = YES;
        [header addSubview:whiteView];
        top = whiteView.bottom + 15;
        

        
        if (!self.text_view) {
            self.text_view = [[STTools_TextView alloc] initWithFrame:CGRectMake(10, 10, whiteView.width - 20, 160)];
            self.text_view.placeholder = @"..正文";
            self.text_view.label.left = 15;
            self.text_view.label.top = 5;
            self.text_view.backgroundColor = UIColor.clearColor;
        }
        [whiteView addSubview:self.text_view];
        whiteView.height = 180;
        top = whiteView.bottom + 10;


    });
    
    if (self.is_add_note) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.title = @"添加笔记";
            self.text_view.placeholder = @"..写评论";
            self.dataSouce = NSMutableArray.new;
            [self.tableView reloadData];
            self.titleTextFiled.hidden = YES;

            
        });
        header.height = self.text_view.bottom + 10;
        self.tableView.tableHeaderView = header;
        
        return;;
    }
    if (!self.autoView) {
        __weak typeof(self) weakSelf =  self;
        self.autoView = [[STTools_ImageAutoChoseView alloc] initWithFrame:CGRectMake(12,top, UISCREEN_WIDTH - 24, 105)];
        [self.autoView setFrameDidChangedHandle:^(STTools_ImageAutoChoseView *autochoseView) {
            [weakSelf config_tableHeader];
        }];
    }
    
    [header addSubview:self.autoView];
    
    header.height = self.autoView.bottom + 10;
    self.tableView.tableHeaderView = header;
}

#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    [cell setSt_tableEasyModel:model];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    __weak typeof(self) weakSelf =  self;
    if ([model.textString isEqualToString:@"分类"]) {
        [THTreeHoleDataController stoneobs_fun_get_home_cates_type:@"1" handle:^(NSArray * _Nonnull cates) {
            NSArray * cates_name = [cates stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
            if (cates.count == 0) {
                return;;
            }
            STTools_PickerViewController * picker = [[STTools_PickerViewController alloc] initWithPickerArray:@[cates_name] andWithHandle:^(NSArray<NSString *> *stringArray) {
               
                NSString * chosed_name = stringArray.lastObject;
                NSInteger index = [cates_name indexOfObject:chosed_name];
                THTieZiCateModel * smodel = cates[index];
                self.posts_cate_id = smodel.t_id;
                model.detailString = chosed_name;
                [self.tableView reloadData];
            }];
            [self presentViewController:picker animated:NO completion:nil];
        }];
    }
    if ([model.textString isEqualToString:@"谁可以看"]) {
        NSArray * array = @[@"自己",@"所有人"];
        STTools_ActionSheet * sheet = [STTools_ActionSheet stoneobs_fun_actionSheetWithTitle:@"谁可以看" buttonTitles:array cancelTitle:@"取消" handle:^(NSInteger index) {
            weakSelf.is_show = @(index).description;
            model.detailString = array[index];
            [weakSelf.tableView reloadData];
        }];
        [sheet show];
    }
    if ([model.textString isEqualToString:@"添加购买体验"]) {
        
        //获取已购商品
        [THTreeHoleDataController stoneobs_fun_get_did_buy_goos:^(NSArray * _Nonnull cates) {
            NSArray * cates_name = [cates stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
            if (cates_name.count == 0) {
                [SVProgressHUD showInfoWithStatus:@"您暂未购买任何商品哟"];
                return;
            }
            STTools_PickerViewController * picker = [[STTools_PickerViewController alloc] initWithPickerArray:@[cates_name] andWithHandle:^(NSArray<NSString *> *stringArray) {
               
                NSString * chosed_name = stringArray.lastObject;
                NSInteger index = [cates_name indexOfObject:chosed_name];
                THTieZiCateModel * smodel = cates[index];
                self.goods_id = smodel.t_id;
                model.detailString = chosed_name;
                [self.tableView reloadData];
            }];
            [self presentViewController:picker animated:NO completion:nil];
        }];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    if (self.titleTextFiled.text.length) {
    }else{
        if (!self.is_add_note) {
            [SVProgressHUD showInfoWithStatus:@"请输入标题"];
            return;
        }

    }
    
    if (self.text_view.text.length) {
    }else{
        [SVProgressHUD showInfoWithStatus:@"请输入正文"];
        return;
    }
    if (self.is_add_note) {
        [SVProgressHUD showSuccessWithStatus:@"添加笔记成功"];
        return;
    }
    
    if (!self.posts_cate_id.length) {
        [SVProgressHUD showInfoWithStatus:@"请选择分类"];
        return;;
    }
    if (self.autoView.stoneobs_fun_get_allImages.count) {
        NSArray * imag_array = self.autoView.stoneobs_fun_get_allImages;
        [TMQNUploadManger.manger uploadMoreImage:imag_array handle:^(BOOL success, NSArray * _Nonnull array) {
            if (array.count == imag_array.count) {
                if (self.model) {
                    [self send_edit_request_urls:array.mj_JSONString];
                }else{
                    [self send_add_suggest_request_urls:array.mj_JSONString];
                }
                
            }else{
               [SVProgressHUD showErrorWithStatus:@"上传失败请重试"];
            }
        }];
    }else{
        if (self.model) {
            [self send_edit_request_urls:@""];
        }else{
            [self send_add_suggest_request_urls:@""];
        }
        return;
        [SVProgressHUD showInfoWithStatus:@"请选择照片"];
        return;
    }
}
- (void)send_add_suggest_request_urls:(NSString*)urls{
    
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (urls.length) {
        [stoneobs_net_param_dic setObject:urls forKey:@"imgs"];
    }
    if (self.text_view.text.length) {
        [stoneobs_net_param_dic setObject:self.text_view.text forKey:@"content"];
    }
    if (self.titleTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.titleTextFiled.text forKey:@"title"];
    }
    if (self.goods_id.length) {
        [stoneobs_net_param_dic setObject:self.goods_id forKey:@"goods_id"];
    }
    [stoneobs_net_param_dic setObject:@"1" forKey:@"type"];//类型 1 =>咨询 2=>视频
    [stoneobs_net_param_dic setObject:self.is_show forKey:@"is_show"];
    [stoneobs_net_param_dic setObject:self.posts_cate_id forKey:@"posts_cate_id"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/publish"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
//编辑
- (void)send_edit_request_urls:(NSString*)urls{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (urls.length) {
        [stoneobs_net_param_dic setObject:urls forKey:@"imgs"];
    }
    if (self.text_view.text.length) {
        [stoneobs_net_param_dic setObject:self.text_view.text forKey:@"content"];
    }
    if (self.titleTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.titleTextFiled.text forKey:@"title"];
    }
    if (self.goods_id.length) {
        [stoneobs_net_param_dic setObject:self.goods_id forKey:@"goods_id"];
    }
    if (self.model.t_id.length) {
        [stoneobs_net_param_dic setObject:self.model.t_id forKey:@"id"];
        
    }
    [stoneobs_net_param_dic setObject:@"1" forKey:@"type"];//类型 1 =>咨询 2=>视频
    [stoneobs_net_param_dic setObject:self.is_show forKey:@"is_show"];
    [stoneobs_net_param_dic setObject:self.posts_cate_id forKey:@"posts_cate_id"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/edit"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
